<template>
  <div class="dialog">
    <el-dialog :model-value="show" title="添加类型" @close="emit('chean')">
      <el-form :model="form" :rules="rules">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="emit('chean')">取消</el-button>
          <el-button type="primary" @click="submitFn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { reactive, ref, watch } from "vue";
import { productAttrcreateApi, productAttrupdateApi } from "../api/api";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
  name: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["chean"]);

const form = reactive<userListModel>({
  name: "",
});
const rules = {
  name: [{ required: true, trigger: "blur", message: "请填写类型名称" }],
};
watch(
  () => props.id,
  () => {
    if (props.id !== 0) {
      form.name = props.name;
      form.id = props.id;
      console.log(props.name);
      console.log(props.id);
    } else {
      form.id = 0;
      form.name = "";
    }
  }
);
// 编辑
const editUser = () => {
  productAttrupdateApi(form).then((res) => {
    if (res.code === 200) {
      ElMessage.success("修改成功");
      form.name = ""
      emit("chean");
    }
  });
};

// 添加
const addUser = () => {
  productAttrcreateApi(form).then((res) => {
      if (res.code === 200) {
        ElMessage.success("添加成功");
        form.name = "";
        emit("chean");
      }
    });
};
const formRef = ref<FormInstance>();

const submitFn = () => {
  // 再做一次数据的校验
  if (props.id !== 0) {
    editUser()
  } else {
    addUser()
  }
  //  如果是添加
};
</script>
<style scoped lang="less">
.dialog {
  :deep(.dialog) {
    width: 100px;
  }
}
</style>
